package com.basin.common.mongo.base;

import com.anwen.mongo.conditions.query.LambdaQueryChainWrapper;
import com.anwen.mongo.model.PageParam;
import com.anwen.mongo.model.PageResult;
import com.anwen.mongo.service.IService;
import com.basin.common.core.response.ResponseResult;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * @author: Sam ZHONG | sammy1997@aliyun.com
 */
public class MongoBasicController<S extends IService<T>, T extends MongoBasicEntity> {
    private S service;

    @Resource
    public void setService(S service) {
        this.service = service;
    }

    @PostMapping("/add")
    public ResponseResult<Boolean> add(@RequestBody T entity) {
        beforeAdd(entity);
        boolean save = service.save(entity);
        afterAdd(entity);
        return ResponseResult.success(save);
    }

    @PostMapping("/update")
    public ResponseResult<Boolean> update(@RequestBody T entity) {
        beforeUpdate(entity);
        Boolean result = service.updateById(entity);
        afterUpdate(entity);
        return ResponseResult.success(result);
    }

    @PostMapping("/delete")
    public ResponseResult<Boolean> delete(@RequestBody T entity) {
        beforeDelete(entity);
        Boolean result = service.removeById(entity.getId());
        afterDelete(entity);
        return ResponseResult.success(result);
    }

    @PostMapping("/query")
    public ResponseResult<PageResult<T>> query(@RequestBody T entity) {
        beforeQuery(entity);
        // 分页
        PageParam pageParam = new PageParam();
        pageParam.setPageNum(entity.getCurrent());
        pageParam.setPageSize(entity.getSize());
        // 查询条件
        LambdaQueryChainWrapper<T> wrapper = buildQueryWrapper(entity);
        PageResult<T> resP;
        if (wrapper != null) {
            resP = service.page(wrapper, pageParam);
        } else {
            resP = service.page(pageParam);
        }
        afterQuery(entity);
        return ResponseResult.success(resP);
    }

    public LambdaQueryChainWrapper<T> buildQueryWrapper(T entity) {
        return null;
    }

    public void beforeAdd(T entity) {
    }

    public void afterAdd(T entity) {
    }

    public void beforeUpdate(T entity) {
    }

    public void afterUpdate(T entity) {
    }

    public void beforeDelete(T entity) {
    }

    public void afterDelete(T entity) {
    }

    public void beforeQuery(T entity) {
    }

    public void afterQuery(T entity) {
    }
}
